package handler

import (
	"awesomeProject/dao"
	"awesomeProject/pojo"
	"awesomeProject/utils"
	"encoding/json"
	"fmt"
	"log"
	"net/http"
	"strconv"
	"time"
)

var pageSizeInt = 10

// 以json方式返回books列表
func BooksHandler(w http.ResponseWriter, r *http.Request) {
	defer func() {
		if err := recover(); err != nil {
			log.Printf("理器发生panic: %v", err)
			utils.CustomError(w, "理器发生panic", http.StatusInternalServerError)
		}
	}()

	switch r.Method {
	case http.MethodGet:
		//解析是第几页。
		values := r.URL.Query()
		page := values.Get("page") // 查询第几页数据

		fmt.Println("page", page)
		if page == "" {
			page = "1"
		}
		pageInt, err := strconv.Atoi(page)
		// 计算偏移量
		offset := (pageInt - 1) * pageSizeInt

		// 获取分页图书列表
		rows, err := dao.Db.Query(
			`SELECT book_id, isbn, title, author, publisher, 
            publish_date, stock FROM books order by book_id desc 
            LIMIT ? OFFSET ?`,
			pageSizeInt, offset)
		if err != nil {
			utils.CustomError(w, err.Error(), http.StatusInternalServerError)
			return
		}
		defer rows.Close()

		var books []pojo.Book
		var tmpTime time.Time
		for rows.Next() {
			var b pojo.Book

			err := rows.Scan(&b.BookID, &b.ISBN, &b.Title, &b.Author,
				&b.Publisher, &tmpTime, &b.Stock)
			if err != nil {
				utils.CustomError(w, err.Error(), http.StatusInternalServerError)
				return
			}
			b.PublishDate = tmpTime.Format("2006-01-02")
			books = append(books, b)
		}

		// 获取总记录数
		var total int
		err = dao.Db.QueryRow("SELECT COUNT(*) FROM books").Scan(&total)
		if err != nil {
			utils.CustomError(w, err.Error(), http.StatusInternalServerError)
			return
		}

		// 返回分页结果
		json.NewEncoder(w).Encode(map[string]interface{}{
			"status":       0,
			"msg":          "OK",
			"data":         books,
			"current_page": pageInt,
			"page_size":    pageSizeInt,
			"total_items":  total,
			"total_pages":  (total-1)/pageSizeInt + 1,
		})
	default:
		utils.CustomError(w, "方法不允许", http.StatusMethodNotAllowed)
	}
}

func BookAddHandler(w http.ResponseWriter, r *http.Request) {
	defer func() {
		if err := recover(); err != nil {
			log.Printf("理器发生panic: %v", err)
			utils.CustomError(w, "理器发生panic", http.StatusInternalServerError)
		}
	}()

	switch r.Method {
	case http.MethodPost:
		// 创建新图书
		var book pojo.Book

		if err := json.NewDecoder(r.Body).Decode(&book); err != nil {
			utils.CustomError(w, "传递参数错误", http.StatusBadRequest)
			return
		}
		userID := r.Context().Value("user_id").(int)

		_, err := dao.Db.Exec(`INSERT INTO books 
            (isbn, title, author, publisher, publish_date, stock,created_by) 
            VALUES (?, ?, ?, ?, ?, ?, ?)`,
			book.ISBN, book.Title, book.Author, book.Publisher,
			book.PublishDate, book.Stock, userID)
		if err != nil {
			utils.CustomError(w, "创建图书信息失败："+err.Error(), http.StatusInternalServerError)
			return
		}
		utils.CustomSucc(w)
	default:
		utils.CustomError(w, "方法不允许", http.StatusMethodNotAllowed)
	}
}

func BookUpdateHandler(w http.ResponseWriter, r *http.Request) {
	defer func() {
		if err := recover(); err != nil {
			log.Printf("理器发生panic: %v", err)
			utils.CustomError(w, "理器发生panic", http.StatusInternalServerError)
		}
	}()

	switch r.Method {
	case http.MethodPut:
		// 更新图书信息
		var book pojo.Book
		if err := json.NewDecoder(r.Body).Decode(&book); err != nil {
			utils.CustomError(w, "传递参数错误", http.StatusBadRequest)
			return
		}

		// 验证必要字段
		if book.BookID == 0 {
			utils.CustomError(w, "BookID 没有传过来", http.StatusBadRequest)
			return
		}

		// 执行更新操作
		_, err := dao.Db.Exec(`UPDATE books SET 
            isbn = ?,
            title = ?,
            author = ?,
            publisher = ?,
            publish_date = ?,
            stock = ?
            WHERE book_id = ?`,
			book.ISBN, book.Title, book.Author, book.Publisher,
			book.PublishDate, book.Stock, book.BookID)

		if err != nil {
			utils.CustomError(w, "更新图书信息失败: "+err.Error(), http.StatusInternalServerError)
			return
		}

		utils.CustomSucc(w)
	default:
		utils.CustomError(w, "方法不允许", http.StatusMethodNotAllowed)
	}
}

func BookDelHandler(w http.ResponseWriter, r *http.Request) {
	defer func() {
		if err := recover(); err != nil {
			log.Printf("理器发生panic: %v", err)
			utils.CustomError(w, "理器发生panic", http.StatusInternalServerError)
		}
	}()

	switch r.Method {
	case http.MethodDelete:
		// 获取要删除的图书ID
		bookID := r.URL.Query().Get("book_id")
		if bookID == "" {
			utils.CustomError(w, "参数缺失", http.StatusBadRequest)
			return
		}

		// 转换为数字
		bookIDInt, err := strconv.Atoi(bookID)
		if err != nil || bookIDInt < 1 {
			utils.CustomError(w, "参数错误", http.StatusBadRequest)
			return
		}

		// 执行删除操作
		result, err := dao.Db.Exec("DELETE FROM books WHERE book_id = ?", bookIDInt)
		if err != nil {
			utils.CustomError(w, "删除失败: "+err.Error(), http.StatusInternalServerError)
			return
		}

		// 检查是否实际删除了记录
		rowsAffected, _ := result.RowsAffected()
		if rowsAffected == 0 {
			utils.CustomError(w, "未找到图书信息。", http.StatusNotFound)
			return
		}

		utils.CustomSucc(w)
	default:
		utils.CustomError(w, "方法不允许", http.StatusMethodNotAllowed)
	}
}
